package com.atguigu.orderService.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.orderService.entity.Order;
import com.atguigu.orderService.entity.PayLog;
import com.atguigu.orderService.mapper.OrderMapper;
import com.atguigu.orderService.mapper.PayLogMapper;
import com.atguigu.orderService.service.OrderService;
import com.atguigu.orderService.service.PayLogService;
import com.atguigu.orderService.utils.HttpClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import org.aspectj.weaver.ast.Or;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author Chen Wen bo
 * @since 2021-08-20
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

    @Resource
    private OrderMapper orderMapper;

    //生成二维码
    @Override
    public Map<String, Object> createNative(String orderId) {
        try {
            //根据订单号查询订单信息
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("order_no",orderId);
            Order order = orderMapper.selectOne(orderQueryWrapper);
            //使用map集合设置二维码需要的参数
            Map<String,String> map = new HashMap<>();
            map.put("appid","wx74862e0dfcf69954");
            map.put("mch_id", "1558950191");
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            map.put("body", order.getCourseTitle());
            map.put("out_trade_no", orderId);
            map.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            map.put("spbill_create_ip", "127.0.0.1");
            map.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            map.put("trade_type", "NATIVE");
            //发送httpClient请求，传递参数XML格式的，微信提供固定的请求地址
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(map,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            httpClient.setHttps(true);
            httpClient.post();
            //得到发送请求返回的结果
            String content = httpClient.getContent();   //是以XML格式返回的
            Map<String,String> resultMap = WXPayUtil.xmlToMap(content);
            Map<String,Object> result = new HashMap<>();
            result.put("out_trade_no", orderId);
            result.put("course_id", order.getCourseId());
            result.put("total_fee", order.getTotalFee());
            result.put("result_code", resultMap.get("result_code"));
            result.put("code_url", resultMap.get("code_url"));
            return result;
        }catch (Exception e){
            throw new RuntimeException();
        }
    }

    //根据订单号查询订单状态
    @Override
    public Map<String, String> queryPayStatus(String orderId) {
        try {
            //1、封装参数
            Map<String,String> m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderId);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            //6、转成Map
            //7、返回
            return WXPayUtil.xmlToMap(xml);
        }catch (Exception e){
            throw new RuntimeException();
        }
    }

    //向支付表中添加支付记录，更新订单状态
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //获取订单id
        String orderNo = map.get("out_trade_no");
        //根据订单id查询订单信息
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        Order order = orderMapper.selectOne(wrapper);

        if(order.getStatus() == 1) return;
        order.setStatus(1);
        orderMapper.updateById(order);

        //记录支付日志
        PayLog payLog=new PayLog();
        payLog.setOrderNo(order.getOrderNo());//支付订单号
        payLog.setPayTime(new Date());
        payLog.setPayType(1);//支付类型
        payLog.setTotalFee(order.getTotalFee());//总金额(分)
        payLog.setTradeState(map.get("trade_state"));//支付状态
        payLog.setTransactionId(map.get("transaction_id"));
        payLog.setAttr(JSONObject.toJSONString(map));
        baseMapper.insert(payLog);//插入到支付日志表
    }
}
